import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.net.*;
/**
 * Sample application using Frame.
 *
 * @author 
 * @version 1.00 13/11/22
 */
public class CoopagriChatFrame extends JFrame {
    
    Panel pan1;
	Panel pan2;
	TextField tbxLogin;
	TextField tbxPass;
	Label etiquetadirIP;
	Label etiquetaPuerto;
	JButton botonAceptar;
	JButton botonCancelar;
	Dialog ventNuevaConex = null;
    	
    /**
     * The constructor.
     */  
     public CoopagriChatFrame() {
                
        
        
        MenuBar menuBar = new MenuBar();
        Menu menuFile = new Menu();
        MenuItem menuFileExit = new MenuItem();
        
        menuFile.setLabel("File");
        menuFileExit.setLabel("Exit");
        
        // Add action listener.for the menu button
        menuFileExit.addActionListener
        (
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    CoopagriChatFrame.this.windowClosed();
                }
            }
        ); 
        menuFile.add(menuFileExit);
        menuBar.add(menuFile);
        
        setTitle("CoopagriChat");
        setMenuBar(menuBar);
        setSize(new Dimension(400, 400));
        
        // Add window listener.
        this.addWindowListener
        (
            new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    CoopagriChatFrame.this.windowClosed();
                }
            }
        );  
        
        
        getAutenticacion();
    }
    
    
    /**
     * Shutdown procedure when run as an application.
     */
    protected void windowClosed() {
    	
    	// TODO: Check if it is safe to close the application
    	
        // Exit application.
        System.exit(0);
    }
    
    public void cargarContactos(int idOrigen){
    	
    	FlowLayout flow = new FlowLayout();
    	JPanel panel = new JPanel(flow);
    	this.add(panel);
    	
    	JButton button;
    	
		try{
    		Connection conn = DriverManager.getConnection ("jdbc:mysql://MIGUEL-I7/soportecoop","root", "softmed");
	    	Statement stmt = null;
			ResultSet rs = null;
					
			stmt = conn.createStatement();
			
			if (stmt.execute("SELECT ID,NOMBRE,IP,PUERTO,ESTADO FROM USUARIO")) {
//	    			System.out.println("cargarContactos4");
				rs = stmt.getResultSet();
				
				while(rs.next()){
					
					button = new JButton(rs.getString("NOMBRE"));
					final int puerto = 5000;
					final String ip = rs.getString("IP");
					final String usuario = rs.getString("NOMBRE");
					final int idDestino = rs.getInt("ID");
					final int _idOrigen = idOrigen;
					button.addActionListener(
						 new ActionListener() {
				                public void actionPerformed(ActionEvent e) {
				                    new VentanaChat(puerto,ip,usuario,_idOrigen,idDestino);
				                }
				            }
						);
					panel.add(button);
				}
			}				
    	}
    	catch(SQLException ex){
    		System.out.println("EXcargarContactos: "+ex.getMessage());
    	}  
    }
    
	public void getAutenticacion(){

    	pan1 = new Panel();
        pan2 = new Panel();
    	ventNuevaConex = new Dialog(this, "Conectar con otro terminal", true);
        ventNuevaConex.setLayout(new BorderLayout());     
        ventNuevaConex.add("Center", pan1);
        ventNuevaConex.add("South", pan2);
        ventNuevaConex.setBounds(300, 300, 270, 100);
        ventNuevaConex.setResizable(false);
        ventNuevaConex = new Dialog(this, "Conectar con otro terminal", true);
        ventNuevaConex.setLayout(new BorderLayout());
        ventNuevaConex.add("Center", pan1);
        ventNuevaConex.add("South", pan2);

        tbxLogin = new TextField("");
        tbxPass = new TextField("");
        etiquetadirIP = new Label("usuario");
        etiquetaPuerto = new Label("pass");
        botonAceptar = new JButton("Aceptar");
        final Dialog f = ventNuevaConex;
        botonAceptar.addActionListener(
			new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                	
					try{
			    		Connection conn = DriverManager.getConnection ("jdbc:mysql://MIGUEL-I7/soportecoop","root", "softmed");
				    	Statement stmt = null;
						ResultSet rs = null;
								
						stmt = conn.createStatement();
						System.out.println("SELECT ID,NOMBRE,IP,PUERTO,ESTADO FROM USUARIO WHERE LOGIN = '" + tbxLogin.getText() + "' AND PASSWORD = '" + tbxPass.getText() + "'");
						if (stmt.execute("SELECT ID,NOMBRE,IP,PUERTO,ESTADO FROM USUARIO WHERE LOGIN = '" + tbxLogin.getText() + "' AND PASSWORD = '" + tbxPass.getText() + "'")) {
			//	    			System.out.println("cargarContactos4");
							rs = stmt.getResultSet();
							
							if(rs.next()){
								f.setVisible(false);
                    			cargarContactos(rs.getInt("ID"));
                    			try{
									stmt = conn.createStatement();
									stmt.executeUpdate("UPDATE USUARIO SET IP = '" + Inet4Address.getLocalHost().getHostAddress().toString() + "', puerto = 5001 WHERE login = '" + tbxLogin.getText() + "';");                    				
                    				//System.out.println(		Inet4Address.getLocalHost().getHostAddress().toString());
                    			}catch(UnknownHostException netEx){
                    			}
                    			
                    			//new Conex("127.0.0.0",5000);
							}
						}				
			    	}
			    	catch(SQLException ex){
			    		System.out.println("EXcargarContactos: "+ex.getMessage());
			    	}  
                    
                }
            }        	
    	);
        botonCancelar = new JButton("Cancelar");
        pan1.setLayout(new GridLayout(2, 2));
        pan1.add(etiquetadirIP);
        pan1.add(tbxLogin);
        pan1.add(etiquetaPuerto);
        pan1.add(tbxPass);
        pan2.add(botonAceptar);
        pan2.add(botonCancelar);       
        ventNuevaConex.setBounds(300, 300, 270, 100);
        ventNuevaConex.setResizable(false);
		ventNuevaConex.setVisible(true);
    }
}